package com.merlin.security.core.validate.code;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import com.merlin.security.core.properties.SecurityProperties;


/**
 * 
 * @author merlin
 *
 */
@RestController
public class ValidateCodeController {
	
	public static final String SESSION_KEY="SESSION_KEY_IMAGE_CODE";
	
	/**
	 * session工具类
	 */
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
	
	@Autowired
	private ValidateCodeGenerator imageCodeGenerator;
	
	
	@GetMapping("/code/image")
	public void createCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
		//根据随机数生成验证码
		ImageCode imageCode = imageCodeGenerator.generate(new ServletWebRequest(request));
		//将随机数传入到session中
		//第一个参数，将请求传入进去sessionStrategy去拿request
		//第二个参数，key
		//第三个参数, value
		sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
		
		//将生成的图片写到接口的响应中
		//第一个参数图片，第二个参数：格式，第三个参数：写入到响应流中
		ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
	}

}
